package cn.chenmanman.system.service.impl;

import cn.chenmanman.model.system.SysRole;
import cn.chenmanman.model.system.SysUserRole;
import cn.chenmanman.model.vo.AssginRoleVo;
import cn.chenmanman.model.vo.SysRoleQueryVo;
import cn.chenmanman.system.mapper.SysRoleMapper;
import cn.chenmanman.system.mapper.SysUserRoleMapper;
import cn.chenmanman.system.service.SysRoleService;
import cn.chenmanman.system.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public IPage<SysRole> selectPage(Page<SysRole> rolePage, SysRoleQueryVo sysRoleQueryVo) {
        return baseMapper.selectPage(rolePage, sysRoleQueryVo);
    }

    @Override
    public Map<String, Object> getUserRoles(String userid) {
        // 获取全部角色
        List<SysRole> sysRoleAll = baseMapper.selectList(null);

        // 获取用户所拥有的角色

        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userid);
        List<String> userRoles = sysUserRoleMapper.selectList(wrapper)
                .stream()
                .map(sysUserRole -> sysUserRole.getRoleId()).collect(Collectors.toList());

        // 塞入map返回
        Map<String, Object> roleMap = new HashMap<>();
        roleMap.put("allRole", sysRoleAll);
        roleMap.put("userRole", userRoles);

        return roleMap;
    }

    @Override
    public void assginRoles(AssginRoleVo assginRoleVo) {
        // 先删掉之前所分配的角色，然后重新分配角色.
        QueryWrapper<SysUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", assginRoleVo.getUserId());
        sysUserRoleMapper.delete(wrapper);

        // 遍历 roleIds，来分配
        for (String id: assginRoleVo.getRoleIdList()) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(assginRoleVo.getUserId());
            sysUserRole.setRoleId(id);
            sysUserRoleMapper.insert(sysUserRole);
        }
    }
}
